<template>
  <view class="bodyView">
    <form>
      <view class="cu-form-group margin-top">
        <view class="title">账号类型</view>
        <view class="radio-group">
          <view class="radio" :class="{'checked': member.userType == '1'}" style="margin-right: 10rpx;" @tap="member.userType=1">区域合伙人</view>
          <view class="radio" :class="{'checked': member.userType == '2'}" @tap="member.userType=2">商户</view>
        </view>
      </view>

      <view class="cu-form-group">
        <view class="title">头像</view>
        <button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
          <image class="avatar img-boder" :src="member.url"></image>
        </button>
      </view>
      <view class="cu-form-group ">
        <view class="title">姓名</view>
        <input type="nickname" maxlength="10" placeholder-style="color:#999;font-size:14px;" placeholder="请填写姓名"
               v-model="member.name"  @blur="nameBlur" />
      </view>
      <view class="cu-form-group ">
        <view class="title">手机号码</view>
        <input type="text" maxlength="11" placeholder-style="color:#999;font-size:14px;" v-model="member.phone" placeholder="请填写手机号码" @blur="phoneBlur">
      </view>
      <button class="cu-btn block margin-tb-sm lg text-custom-bg text-white btn" @click="save">确认</button>
    </form>

  </view>
</template>

<script setup lang="ts">
import env from '@/common/utils/env';
import {onMounted, ref, reactive, computed} from "vue";
import { registerUser, getUser} from "@/common/api/user";
import {useStore} from "../../common/store";
import { onLoad ,onShow} from '@dcloudio/uni-app';

import {redirectToPage, navigateToPage, switchTabPage} from '@/common/utils/redirectPage'

const store = useStore();
const token = computed(() => store.token)


// 非ts写法

const emit = defineEmits(["closeBooking"])
const openid = ref('')

const oraUrlPage = ref('')
const redirectType  = ref('')
const otPromoCode = ref('')

// 用户信息
const member = reactive({
  url: '',
  username: '',
  phone:'',
  userType:'1',
  openId: token.value,
  pass: '12345678',
  pass2: '12345678',
  adminLevel: 1,
  otPromoCode: '',
  email: '',
  name: ''
});

const storeNo = ref('');
const startDate = ref('');
const endDate = ref('')

const storeList = ref([]);
const showStore = ref(false)

const getDate = (type) => {
  const date = new Date();
  let year: any = date.getFullYear();
  let month: any = date.getMonth() + 1;
  let day: any = date.getDate();

  if (type === 'start') {
    year = year - 60;
  } else if (type === 'end') {
    year = year + 2;
  }
  month = month > 9 ? month : '0' + month;
  day = day > 9 ? day : '0' + day;
  return `${year}-${month}-${day}`;
}

// const handleDateChange = (e) => {
//   member.birthday = e.target.value
// }

const onChooseAvatar =(e) =>{
  uni.uploadFile({
  			url: `${env.baseurl}/api/user/uploadImage`,
  			filePath:  e.detail.avatarUrl,
  			name: 'file',
  			success: (uploadFileRes) => {
				const data = JSON.parse(uploadFileRes.data);
				if(data && data.code == '200') {
					member.url = data.data.url
				} else {
					uni.showToast({
					  title: '头像上传失败,请重试！',
					  duration: 2000,
					  icon: 'none'
					});
				}
  			}
  		});
}

// const changNick =(e) =>{
//   member.username = e.detail.value
// }

const getUserStore = async (openid) => {
  await getUser(openid).then(r => {
    if(r && r.data) {
      let res = r.data
      store.$patch({
        avatarUrl: res.url,
        userId: res.id,
        userName: res.name,
        userType: res.userType,
        hasLogin: true,
        phone: res.phone,
        token: openid,
        auditStatus:res.auditStatus,
        adminLevel: res.adminLevel,
        adminLevelName: res.adminLevelName,
        qrcode: res.qrcode,
        promoCode: res.promoCode,
        promoCodeUrl: res.promoCodeUrl,
        upgradePreLevel: res.upgradePreLevel,
        upgradeLevel: res.upgradeLevel,
        upgradeTime: res.upgradeTime,
        city: res.city,
        ownerShop: res.ownerShop
      })
    } else {
      store.$patch({
        avatarUrl: '',
        userId: '',
        userType: '',
        userName: '',
        hasLogin: false,
        phone: '',
        auditStatus:0,
        adminLevel: 0,
        adminLevelName: '',
        qrcode: '',
        promoCode: '',
        promoCodeUrl: '',
        upgradePreLevel: '',
        upgradeLevel: '',
        upgradeTime: '',
        city: '',
        ownerShop: {
          poiId: '',
          poiName: '',
          address:'',
          cardType:'',
          cardStartTime:'',
          cardEndTime:'',
          corporation: '',
          corporationPhone: '',
          storePhone: '',
          businessLicense: '',
          sanitaryLicensePhoto: '',
          sanitaryLicensePhotos: [],
          dredgeDouyin: '',
          dredgeBuy: '',
          businessLicensePhoto: '',
          businessLicensePhotos: [],
          corporationPhoto: '',
          corporationPhotos: [],
          corporationCard: '',
          corporationCardBank: '',
          doorPhoto: '',
          doorPhotos: [],
          evnPhoto: '',
          evnPhotos: [],
          douyinPhoto: '',
          douyinPhotos: [],
          deliveryAddress: '',
          businessHour: ''
        }
      })
    }
  }).catch(e=>{

  })
}


const save = async () => {
  if (!member.url) {
    uni.showToast({
      title: '请上传头像',
      duration: 2000,
      icon: 'none'
    });
    return false
  }

  // if (!member.username) {
  //   uni.showToast({
  //     title: '用户名不能为空',
  //     duration: 2000,
  //     icon: 'none'
  //   });
  //   return false;
  // }
  if (!member.name) {
    uni.showToast({
      title: '姓名不能为空',
      duration: 2000,
      icon: 'none'
    });
    return false;
  }

  if (!member.phone) {
    uni.showToast({
      title: '手机号不能为空',
      duration: 2000,
      icon: 'none'
    });
    return false;
  }

  if (!member.pass) {
    uni.showToast({
      title: '请输入密码!',
      duration: 2000,
      icon: 'none'
    });
    return false;
  }
  if (member.pass.length < 8) {
    uni.showToast({
      title: '密码长度请在8~16之间!',
      duration: 2000,
      icon: 'none'
    });
    return false;
  }

  if (!member.pass2) {
    uni.showToast({
      title: '请确认密码!',
      duration: 2000,
      icon: 'none'
    });
    return false;
  }
  // if (member.pass != member.pass2) {
  //   uni.showToast({
  //     title: '请确保两次输入的密码一致!',
  //     duration: 2000,
  //     icon: 'none'
  //   });
  //   return false;
  // }

  member.username = member.phone
  member.openId = openid.value;
  member.otPromoCode = otPromoCode.value;
  uni.showLoading({
    title: '加载中'
  });
  await registerUser(member).then(res => {
    uni.showToast({
      icon: 'none',
      duration: 3000,
      title: `${res.message}`
    });

    setTimeout(() => {
      uni.hideLoading();
      const oraUrlPage = ref('')
      const redirectType  = ref('')
      getUserStore(member.openId)
      if (oraUrlPage.value && redirectType.value) {
        if (redirectType.value =='switchTab') {
          switchTabPage(oraUrlPage.value)
        } else if (redirectType.value == 'navigateTo') {
          redirectToPage(oraUrlPage.value)
        }
      } else {
        uni.navigateBack({
          delta: 1
        });
      }
    }, 3000)
  })
}

const nameBlur = (e) => {
  member.name = e.detail.value
}

const usernameBlur = (e) => {
	member.username = e.detail.value
	if (!member.username) {
	  uni.showToast({
	    icon: 'none',
	    duration: 3000,
	    title: `请填写用户名`
	  });
	  member.username = ''
	  return
	}
	var reg = /^[A-Za-z0-9]+$/;
	if (!reg.test(member.username)) {
	  uni.showToast({
	    icon: 'none',
	    duration: 3000,
	    title: `用户名为数字字或符串`
	  });
	  member.username = ''
	  return;
	}
}

const phoneBlur = () => {
  if (!member.phone) {
    uni.showToast({
      icon: 'none',
      duration: 3000,
      title: `请填写手机号码`
    });
    return
  }

  var reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
  if (!reg.test(member.phone)) {
    uni.showToast({
      icon: 'none',
      duration: 3000,
      title: `手机号码有误，请重新输入!`
    });
    member.phone= ''
    return;
  }
}

// register
onLoad((options : any) => {
  oraUrlPage.value = options.oraUrlPage
  redirectType.value = options.redirectType
  openid.value = options.openid;
  otPromoCode.value = options.otPromoCode;
})

onMounted(async () => {
  // startDate.value = getDate('start')
  // endDate.value = getDate('end')
  // await findStoreList();
})
</script>

<style lang="scss" scoped>

.bodyView {
  margin: 10rpx;
  .cu-form-group .title {
    min-width: calc(4em + 15px);
  }
  .img-boder{
    border-radius: 50%;
  }
  .radio-group {
    display: flex;
    justify-content: flex-start;

    .radio {
      padding: 10rpx 30rpx;
      border-radius: 10rpx;
      border: 2rpx solid #909090;
      color: #919293;
      font-size: 28rpx;

      &.checked {
        background-color: #EAB769;
        color: #ffffff;
        border: 2rpx solid transparent;
      }
    }
  }
}


.form {
  border-radius: 8rpx;
}

.form-input {
  margin-top: 20rpx;
  .label {
    width: 160rpx;
    font-size: 32rpx   ;
    color: #5A5B5C;
    text-align: right;
    padding-right: 14rpx;
    margin-top: 2rpx;

  }

  .input {
  }

  .radio-group {
    display: flex;
    justify-content: flex-start;

    .radio {
      padding: 10rpx 30rpx;
      border-radius: 6rpx;
      border: 2rpx solid #919293;
      color: #919293;
      font-size: 28rpx;

      &.checked {
        background-color: #ADB838;
        color: #ffffff;
        border: 2rpx solid #ADB838;
      }
    }
  }
}

.d-flex {
  display: flex;
}

.flex-fill {
  -ms-flex: 1 1 auto !important;
  flex: 1 1 auto !important;
  textarea {
    height: 200rpx;
    width: 96%;
  }
}

.w-100 {
  width: 100% !important;
}

.align-items-center {
  align-items: center;
}

.align-items-left {
  align-items: left;
}

.avatar-wrapper {
  padding: 0;
  margin: 0;
  width: 35px !important;
  border-radius: 8px;
}

.avatar {
  display: block;
  width: 35px;
  height: 35px;
  z-index: 1;
}
.button {
  background-color: green;
  margin: 20rpx;
}

.text-area{
  background: #F8F8F8;
  border-radius: 10rpx;
  height: 234rpx;
  padding-top: 20rpx;
  padding-left: 20rpx;
}
.btn{
  margin-bottom: 20rpx;
  margin-right: 30rpx;
  margin-left: 30rpx;
}
</style>
